﻿using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

    [Tooltip("跟踪目标")]
    public Transform Target;
    [Tooltip("跟踪速度")]
    public float Speed = 1f;
    [Tooltip ("左边界")]
    public float maxLeft;
    [Tooltip ("右边界")]
    public float maxRight;

    private float cam_x;
    private float player_x;
    private float player_y;
    private bool canmove = true;
    private Vector3 camPos;

	void Start () {  
	}
	
	void Update () {
        camPos = transform.position;
        cam_x = transform.position.x;
        player_x = Target.position.x;
        player_y = Target.position.y;

        if (cam_x > maxLeft && cam_x < maxRight)
        {
            canmove = true;
        }
        else if (player_x < maxLeft || player_x > maxRight)
            canmove = false;
        else canmove = true;

        if(canmove)
        {
            Follow();
        }
	}

    private void Follow()
    {
        if(player_x != cam_x)
        {
            transform .position  = Vector3.Lerp(camPos,new Vector3(player_x, camPos.y, camPos.z), Speed * Time.deltaTime);
        }
    }
}
